package com.hbpu.maven.spring.tx.service.impl;

import com.hbpu.maven.spring.tx.bean.Book;
import com.hbpu.maven.spring.tx.dao.AccountDao;
import com.hbpu.maven.spring.tx.dao.BookDao;
import com.hbpu.maven.spring.tx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    BookDao bookDao;

    @Autowired
    AccountDao accountDao;

    @Transactional(timeout = 3, rollbackFor = Exception.class)
    @Override
    public void checkout(String username, Integer bookId, Integer buyNumber) throws IOException {
        Book book = bookDao.selectBookById(bookId);

        double v = book.getPrice() * buyNumber;

        accountDao.deductBalanceByUserName(username, v);

        bookDao.updateBookStock(bookId, buyNumber);

//        int i = 10 / 0;
        FileInputStream fileInputStream = new FileInputStream("D:\\text.txt");
        System.out.println(fileInputStream.available());
    }
}
